package cn.hgpu.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Mybatis工具类
 */
public class MybatisUtils {

    private static SqlSession sqlSession;

    static{
        try {
            String resource = "mybatis.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Mapper
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getMapper(Class<T> tClass){
        return sqlSession.getMapper(tClass);
    }

    /**
     * 提交事务
     */
    public static void commit(){
        sqlSession.commit();
    }

    /**
     * 回滚事务
     */
    public static void rollback(){
        sqlSession.rollback();
    }

}